package cifra.protocolo.bluehand;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore.Images;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.facebook.android.AsyncFacebookRunner;
import com.facebook.android.AsyncFacebookRunner.RequestListener;
import com.facebook.android.DialogError;
import com.facebook.android.Facebook;
import com.facebook.android.Facebook.DialogListener;
import com.facebook.android.FacebookError;

import data.LivroData;

public class Resultado extends Activity implements OnClickListener {
	private TextView cifra;
	private Button goNerdstore, copiar, share;
	boolean teste = true; 
	Button login_and_post;
	// Your Facebook APP ID
    private static String APP_ID = "308180782571605"; // Replace your App ID here
 
    // Instance of Facebook Class
    private Facebook facebook;
    private AsyncFacebookRunner mAsyncRunner;
    String FILENAME = "AndroidSSO_data";
    private SharedPreferences mPrefs;
 
	
	
	public String x = "", cifraFinal = "";
	String image_URL;
	ImageView imageView;
	LivroData livro;
	protected int larguraTela, tamanhoExato;

	protected void propriedadesTela() {
		DisplayMetrics dm = new DisplayMetrics();
		getWindowManager().getDefaultDisplay().getMetrics(dm);

		larguraTela = dm.widthPixels;

		if (larguraTela > 550) {
			tamanhoExato = 500;
		} else if (larguraTela < 400 && larguraTela > 250) {
			tamanhoExato = 300;
		} else { // talvez tenha que ser um if else (larguraTela < 250)
			tamanhoExato = 200;
		}
	}

	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setFullScreen(Resultado.this);
		setContentView(R.layout.resultado);

		livro = (LivroData) getIntent().getExtras().getSerializable("livros");
		cifra = (TextView) findViewById(R.id.cifra);
		copiar = (Button) findViewById(R.id.copiar);
		goNerdstore = (Button) findViewById(R.id.goNerdstore);
		share = (Button) findViewById(R.id.share);

		
		
		
		login_and_post = (Button) findViewById(R.id.login_and_post);
		login_and_post.setOnClickListener(this);
		facebook = new Facebook(getString(R.string.APP_ID));
        mAsyncRunner = new AsyncFacebookRunner(facebook);
		
		

		imageView = (ImageView) findViewById(R.id.image);
		goNerdstore.setVisibility(View.GONE);
		// ESTRUTURA DA CIFRA
		// PBH[livros]+[codigoPais]+[codigoCidade]+[posi��oNoGrupo]+[statusProtegido]+[numeroAptidao]

		String protocolos = "", statusProtegido = "", grauNoGrupo = "";
		String[] codigoAreaPais = getResources().getStringArray(
				R.array.codigoAreaPais);

		// LIVROS/PROTOCOLOS LIDOS
		if (livro.isLivroAlienigena() && livro.isLivroZumbi()) {
			protocolos = "az";
		} else if (livro.isLivroZumbi()) {
			protocolos = "z";
		} else if (livro.isLivroAlienigena()) {
			protocolos = "a";
		} else {
			protocolos = "_";
			Toast.makeText(getApplicationContext(),
					getString(R.string.compreCompreCompre).toString(),
					Toast.LENGTH_LONG).show();
			goNerdstore.setVisibility(View.VISIBLE);
		}

		// C�DIGO DE �REA DO PA�S
		// codigoAreaPais[livro.getRegiao().getCodigoPais()].toString()

		// C�DIGO DO DDD DA CIDADE
		// livro.getRegiao().getDdd()

		// Posi��o no Grupo (L�DER/EREMITA/INTEGRANTE)
		switch (livro.getStatusGrupoData().getStatus()) {
		case 0:
			grauNoGrupo = "?";
			// Solit�rio
			break;
		case 1:
			grauNoGrupo = ":";
			// Mero integrante
			break;
		case 2:
			grauNoGrupo = "!";
			break;
		// L�der
		default:
			grauNoGrupo = ":";
			break;
		}

		// � PROTEGIDO?
		if (livro.getStatusGrupoData().isProtegido()) {
			statusProtegido = "*";
		} else {
			statusProtegido = "";
		}

		// PEGA AS APTID�ES ESCOLHDIAS
		// geraAptidoesCifradas();

		cifra.setText("PBH" + protocolos + "+"
				+ codigoAreaPais[livro.getRegiao().getCodigoPais()].toString()
				+ livro.getRegiao().getDdd() + grauNoGrupo + statusProtegido
				+ geraAptidoesCifradas());

		propriedadesTela();
		image_URL = "https://chart.googleapis.com/chart?cht=qr&chs="
				+ tamanhoExato + "x" + tamanhoExato + "&chl="
				+ cifra.getText().toString().replace("+", "%2B");
		// DownloadFilesTask download = new DownloadFilesTask();
		ShareImageTask download = new ShareImageTask(Resultado.this);
		download.execute();

		// BOT�O COPIAR
		copiar.setOnClickListener(this);
				/*
				new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				@SuppressWarnings("deprecation")
				int sdk = android.os.Build.VERSION.SDK_INT;
				if (sdk < 11) {
					android.text.ClipboardManager clipboard = (android.text.ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
					clipboard.setText(cifra.getText());
					Toast.makeText(getApplicationContext(), "Cifra copiada",
							Toast.LENGTH_SHORT).show();
				} else {
					// android.content.ClipboardManager clipboard =
					// (android.content.ClipboardManager)
					// getSystemService(Context.CLIPBOARD_SERVICE);
					// android.content.ClipData clip = ClipData.newPlainText(
					// "simple text", cifra.getText());
					// clipboard.setPrimaryClip(clip);
					Toast.makeText(getApplicationContext(), "Cifra copiada",
							Toast.LENGTH_SHORT).show();
				}
			}
		});
*/
		// BOT�O GO NERDSTORE
		goNerdstore.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View arg0) {
				startActivity(new Intent(Intent.ACTION_VIEW, Uri
						.parse("http://www.nerdstore.com.br/")));
			}
		});

		// BOT�O COMPARTILHAR
		share.setOnClickListener(this);

	}

	private void setFullScreen(Context currContext) {
		((Activity) currContext).requestWindowFeature(Window.FEATURE_NO_TITLE);
		((Activity) currContext).getWindow().setFlags(
				WindowManager.LayoutParams.FLAG_FULLSCREEN,
				WindowManager.LayoutParams.FLAG_FULLSCREEN);
	}

	public String geraAptidoesCifradas() {
		int valor = 0, reajuste = 0;

		for (int i = 0; i < livro.getAptidoesData()
				.getListaAptidoesSelecionadas().size(); i++) {

			valor = (Integer) livro.getAptidoesData()
					.getListaAptidoesSelecionadas().get(i); // Pego o valor da
															// posi��o salva (ou
															// seja, preciso
															// somar 1 na hora
															// de printar)
			reajuste = valor + 1;

			if (reajuste >= 10) {

				if (reajuste == 100) {
					x = x.concat("00");
				} else if (reajuste == 101) {
					x = x.concat("#");
				} else {
					x = x.concat(String.valueOf(reajuste));
				}

			} else {
				switch (valor) {
				case 0:
					x = x.concat("01");
					break;
				case 1:
					x = x.concat("02");
					break;
				case 2:
					x = x.concat("03");
					break;
				case 3:
					x = x.concat("04");
					break;
				case 4:
					x = x.concat("05");
					break;
				case 5:
					x = x.concat("06");
					break;
				case 6:
					x = x.concat("07");
					break;
				case 7:
					x = x.concat("08");
					break;
				case 8:
					x = x.concat("09");
					break;
				default:
					break;
				}
			}
		}
		return x;
	}

	public static Bitmap drawableToBitmap(Drawable drawable) {
		if (drawable instanceof BitmapDrawable) {
			return ((BitmapDrawable) drawable).getBitmap();
		}

		Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(),
				drawable.getIntrinsicHeight(), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmap);
		drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
		drawable.draw(canvas);

		return bitmap;
	}

	public Uri getImageUri(Context inContext, Bitmap inImage) {
		ByteArrayOutputStream bytes = new ByteArrayOutputStream();
		inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
		String path = Images.Media.insertImage(inContext.getContentResolver(),
				inImage, "Title", null);
		return Uri.parse(path);
	}

	public class ShareImageTask extends AsyncTask<String, String, String> {
		private Context context;
		private ProgressDialog pDialog;
		URL myFileUrl;
		Bitmap bmImg = null;
		Intent share;
		public String nomeArquivo;
		File file;

		public ShareImageTask(Context context) {
			this.context = context;
		}

		@Override
		protected void onPreExecute() {
			super.onPreExecute();

			pDialog = new ProgressDialog(context);
			pDialog.setMessage("Downloading Image ...");
			pDialog.setIndeterminate(false);
			pDialog.setCancelable(false);
			pDialog.show();

		}

		@Override
		protected String doInBackground(String... args) {
			try {
				URL url = new URL(image_URL);// myFileUrl = new URL(args[0]);
				myFileUrl = url;
				HttpURLConnection conn = (HttpURLConnection) myFileUrl
						.openConnection();
				conn.setDoInput(true);
				conn.connect();
				InputStream is = conn.getInputStream();
				bmImg = BitmapFactory.decodeStream(is);
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				// EST� SALVANDO S� N�O EST� COMPARTILHANDO
				String path = myFileUrl.getPath();
				// NOME // String idStr = path.substring(path.lastIndexOf('/') +
				// 1);
				File filepath = Environment.getExternalStorageDirectory();
				File dir = new File(filepath.getAbsolutePath()
						+ "/Cifras do Protocolo Bluehand/");
				dir.mkdirs();

				SimpleDateFormat s = new SimpleDateFormat("ddMMyyyyhhmmss");
				String format = s.format(new Date());

				nomeArquivo = "Cifra_do_Protocolo_Bluehand_-"
						+ format.toString() + ".png";
				Passadeira.caminho_e_nome_do_arquivo = nomeArquivo.toString();

				// Log.e("passadeira", "caminho: "
				// + Passadeira.caminho_e_nome_do_arquivo);

				file = new File(dir, nomeArquivo);
				FileOutputStream fos = new FileOutputStream(file);
				bmImg.compress(CompressFormat.JPEG, 75, fos);
				fos.flush();
				fos.close();

			} catch (Exception e) {
				e.printStackTrace();
				Log.e("erro", "erro: " + e.getMessage());
			}

			return null;
		}

		@Override
		protected void onPostExecute(String args) {
			Log.e("Salvou", "salvou? " + file.exists());
			imageView.setImageBitmap(bmImg);
			pDialog.dismiss();

		}

	}

	private void shareSemFacebookEFuncionaSoComImagem() {
		try {

			Intent share = new Intent(Intent.ACTION_SEND);
			share.setType("image/png");

			Log.e("passadeira", "caminho: "
					+ Passadeira.caminho_e_nome_do_arquivo);

			share.putExtra(Intent.EXTRA_TEXT,
					"Minha cifra de acordo com o Protocolo Bluehand �: "
							+ cifra.getText().toString());
			share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file:///"
					+ Environment.getExternalStorageDirectory()
							.getAbsolutePath()
					+ "/Cifras do Protocolo Bluehand/"
					+ Passadeira.caminho_e_nome_do_arquivo)); // Uri.fromFile(getFileStreamPath(Passadeira.caminho_e_nome_do_arquivo))

			startActivity(Intent.createChooser(share,
					"Compartilhar Cifra do Protocolo Bluehand"));
		} catch (Exception e) {
			Log.e("PROBLEMA", "" + e.getMessage());
		}
	}

	@Override
	public void onClick(View v) {

		switch (v.getId()) {
		case R.id.copiar:
			loginToFacebook();
			break;
		case R.id.share:
			postMessageOnWall(Resultado.this, "teste", "Pedro Fsn");
			Log.e("teste", "Compartilhar - tocado");
			break;
		case R.id.login_and_post:
			logout();
			break;
		default:
			break;

		}

	}
	
	public void postMessageOnWall(Activity activity, String message,  String name) {
	    if (facebook.isSessionValid()) {
	        Bundle parameters = new Bundle();
	        parameters.putString("message", message);
//	        parameters.putString("picture", picture);String picture, String caption,
//	        parameters.putString("caption", caption);
	        parameters.putString("name", name);
	        try {
	            String response = facebook.request("me/feed", parameters, "POST");
	            System.out.println(response);
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    }
	}
	
	public void logout() {
		mAsyncRunner.logout(this, new RequestListener() {
	        @Override
	        public void onComplete(String response, Object state) {
	            Log.d("Logout from Facebook", response);
	            if (Boolean.parseBoolean(response) == true) {
	                // User successfully Logged out
	            }
	        }
	 
	        @Override
	        public void onIOException(IOException e, Object state) {
	        }
	 
	        @Override
	        public void onFileNotFoundException(FileNotFoundException e,
	                Object state) {
	        }
	 
	        @Override
	        public void onMalformedURLException(MalformedURLException e,
	                Object state) {
	        }
	 
	        @Override
	        public void onFacebookError(FacebookError e, Object state) {
	        }
	    });
	}

	public void loginToFacebook() {
	    mPrefs = getPreferences(MODE_PRIVATE);
	    String access_token = mPrefs.getString("access_token", null);
	    long expires = mPrefs.getLong("access_expires", 0);
	 
	    if (access_token != null) {
	        facebook.setAccessToken(access_token);
	    }
	 
	    if (expires != 0) {
	        facebook.setAccessExpires(expires);
	    }
	 
	    if (!facebook.isSessionValid()) {
	        facebook.authorize(this,
	                new String[] { "email", "publish_stream", "feed" },
	                new DialogListener() {
	 
	                    @Override
	                    public void onCancel() {
	                        // Function to handle cancel event
	                    }
	 
	                    @Override
	                    public void onComplete(Bundle values) {
	                        // Function to handle complete event
	                        // Edit Preferences and update facebook acess_token
	                        SharedPreferences.Editor editor = mPrefs.edit();
	                        editor.putString("access_token",
	                                facebook.getAccessToken());
	                        editor.putLong("access_expires",
	                                facebook.getAccessExpires());
	                        editor.commit();
	                        
	                        
	                        values.putString("message", "Hi there!!");
	                        values.putString("place", "166793820034304");
	                        try {
								facebook.request(values);
							} catch (MalformedURLException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							} catch (IOException e) {
								// TODO Auto-generated catch block
								e.printStackTrace();
							}
	                    }
	 
	                    @Override
	                    public void onError(DialogError error) {
	                        // Function to handle error
	 
	                    }
	 
	                    @Override
	                    public void onFacebookError(FacebookError fberror) {
	                        // Function to handle Facebook errors
	 
	                    }
	 
	                });
	    } 
	}
	

}
